<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>更换头像</span>
    </div>
    <div>
      <!-- 图片，用来展示用户选择的头像 -->
      <img v-if="avatar" :src="avatar" alt="" />
      <img v-else src="../../../assets/images/avatar.jpg" alt="" />

      <!-- 按钮区域 -->
      <div class="btn-box">
      <input
      type="file"
      accept="image/*"
      style="display: none;"
      ref="fileInp"
      @change="avatarChange" />
      <el-button @click="$refs.fileInp.click()" type="primary"    icon="el-icon-plus">选择图片</el-button>
      <el-button type="success" icon="el-icon-upload"         :disabled="avatar === ''" @click="uploadAvatar">上传头像</el-button>
      </div>
    </div>
  </el-card>
</template>

<script>
export default {
  name: 'UserAvatar',
  data () {
    return {
      avatar: ''
    }
  },
  methods: {
    avatarChange (e) {
      const files = e.target.files
      //   console.log(files) // files 是一个数组 fileList
      if (files.length > 0) {
        // img的src只能设置两种数据,:BASE64(dataurl) 或URL
        // 选择了图片,把图片给用户预览
        // 1.创建一个对象
        const fr = new FileReader()
        // 2.读文件 (异步读取)
        fr.readAsDataURL(files[0])
        // 3.获取结果
        fr.onload = (e) => {
          // 4.设置给 img  的src
          this.avatar = e.target.result
        }
      } else {
        // 用户没有选择图片,取消预览
        // console.log('用户选择了取消')
        this.avatar = ''
      }
    },
    async uploadAvatar () {
      const { data: res } = await this.$http.patch('/my/update/avatar', { avatar: this.avatar })
      if (res.code !== 0) return this.$message.error('上传头像失败！')
      this.$message.success('上传头像成功！')
      this.$store.dispatch('initUserInfo')
    }
  }
}
</script>

<style lang="less" scoped>
.btn-box {
  margin-top: 10px;
}
.preview {
  object-fit: cover;
}
</style>
